<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 头像修改对话框 -->
    <el-dialog v-model="dialogVisible" title="修改头像" width="500">
      <div>
        <div class="flex space-x-4 head-box">
          <div class="relative" style="flex-shrink: 0">
            <img :src="waitAvatar" alt="用户头像" class="w-20 h-20 rounded-full object-cover" />
          </div>
          <div class="recommend-head-box">
            <div class="recommend-head-item" v-for="o in 10"></div>
            <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
              <div class="recommend-head-item">
                <el-icon>
                  <EditPen />
                </el-icon>
              </div>
            </el-upload>
          </div>
        </div>
        <div class="error-tips text-red-500">{{ errorTips }}</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadImg()">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <div class="container mx-auto max-w-5xl p-6">
      <!-- 基本信息 -->
      <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden">
        <div class="section-header flex justify-between items-center p-4 border-b border-gray-200">
          <h2 class="section-title text-lg font-semibold text-gray-800 flex items-center gap-2">
            <i class="fas fa-user text-blue-500"></i> 基本信息
          </h2>
        </div>
        <div class="section-body p-6">
          <div class="avatar-section flex items-center gap-6 mb-8">
            <div class="avatar-container w-24 h-24 rounded-full overflow-hidden relative border-3 border-blue-100">
              <img :src="userInfo.avatar" alt="用户头像" class="avatar-img w-full h-full object-cover">
              <button @click="dialogVisible = true;"
                class="edit-icon absolute bottom-0 right-0 bg-white rounded-full p-1 shadow-md hover:bg-gray-50">
                <el-icon class="text-gray-600">
                  <EditPen />
                </el-icon>
              </button>
            </div>
            <div class="avatar-upload flex flex-col gap-2">
              <p class="avatar-hint text-xs text-gray-500">支持 JPG、PNG 格式，建议尺寸 200x200 像素，不超过 1MB</p>
            </div>
          </div>

          <div class="form-row grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <!-- <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">用户名</label>
              <input type="text" class="form-control p-2 border border-gray-200 rounded-md text-base transition-colors focus:border-blue-500 focus:outline-none w-full" v-model="userInfo.username" disabled>
              <span class="form-text text-xs text-gray-500">用户名不可修改</span>
            </div> -->
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">昵称</label>
              <el-input v-if="isEdit" v-model="userInfoEdit.nickName" class="w-full"></el-input>
              <span v-else>{{ userInfo.nickName }}</span>
            </div>
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">性别</label>
              <el-radio-group v-if="isEdit" v-model="userInfoEdit.sex">
                <el-radio label="1" value="1">男</el-radio>
                <el-radio label="2" value="2">女</el-radio>
                <el-radio label="0" value="0">保密</el-radio>
              </el-radio-group>
              <span v-else>{{ genderText }}</span>
            </div>
          </div>

          <div class="form-row grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">城市</label>
              <el-input v-if="isEdit" v-model="userInfoEdit.city" class="w-full"></el-input>
              <span v-else>{{ userInfo.city }}</span>
            </div>
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">年龄</label>
              <el-input v-if="isEdit" v-model="userInfoEdit.age" class="w-full"></el-input>
              <span v-else>{{ userInfo.age }}</span>
            </div>
            <!-- <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">手机号</label>
              <el-input v-if="isEdit" v-model="userInfoEdit.phone" class="w-full"></el-input>
              <span v-else>{{userInfo.phone}}</span>
            </div> -->
          </div>


          <div class="form-row grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <!-- <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">email</label>
              <el-input v-if="isEdit" v-model="userInfoEdit.email" class="w-full"></el-input>
              <span v-else>{{userInfo.email}}</span>
            </div> -->
            <div class="form-group flex flex-col gap-1 mb-6">
              <label class="form-label text-sm font-medium text-gray-500">签名</label>
              <el-input v-if="isEdit" type="textarea" v-model="userInfoEdit.signature" :rows="3"
                class="w-full"></el-input>
              <span v-else>{{ userInfo.signature }}</span>
            </div>
          </div>



          <div class="form-actions flex justify-end gap-4 mt-8">
            <template v-if="isEdit">
              <el-button @click="cancelEdit" style="width: 120px;">取消</el-button>
              <el-button type="primary" @click="saveBasicInfo" style="width: 120px;">保存修改</el-button>
            </template>
            <template v-else>
              <el-button type="primary" @click="startEdit" style="width: 120px;">编辑资料</el-button>
            </template>
          </div>
        </div>
      </div>

      <!-- 企业信息 -->
      <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden" v-if="false">
        <div class="section-header flex justify-between items-center p-4 border-b border-gray-200">
          <h2 class="section-title text-lg font-semibold text-gray-800 flex items-center gap-2">
            <i class="fas fa-building text-blue-500"></i> 企业信息
          </h2>
        </div>
        <div class="section-body p-6">
          <div class="form-row grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">企业名称</label>
              <el-input v-if="isCompanyEdit" v-model="companyInfoEdit.name" class="w-full"></el-input>
              <span v-else>{{ companyInfo.name }}</span>
            </div>
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">职位</label>
              <el-input v-if="isCompanyEdit" v-model="companyInfoEdit.position" class="w-full"></el-input>
              <span v-else>{{ companyInfo.position }}</span>
            </div>
          </div>

          <div class="form-row grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">企业规模</label>
              <el-select v-if="isCompanyEdit" v-model="companyInfoEdit.scale" class="w-full">
                <el-option v-for="(scale, index) in companyScales" :key="index" :label="scale"
                  :value="scale"></el-option>
              </el-select>
              <span v-else>{{ companyInfo.scale }}</span>
            </div>
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">成立时间</label>
              <el-date-picker v-if="isCompanyEdit" v-model="companyInfoEdit.foundedDate" type="date"
                class="w-full"></el-date-picker>
              <span v-else>{{ companyInfo.foundedDate }}</span>
            </div>
          </div>

          <div class="form-group flex flex-col gap-1 mb-6">
            <label class="form-label text-sm font-medium text-gray-500">企业简介</label>
            <el-input v-if="isCompanyEdit" type="textarea" v-model="companyInfoEdit.description" rows="3"
              class="w-full"></el-input>
            <span v-else>{{ companyInfo.description }}</span>
          </div>

          <div class="form-actions flex justify-end gap-4 mt-8">
            <template v-if="isCompanyEdit">
              <el-button @click="cancelCompanyEdit">取消</el-button>
              <el-button type="primary" @click="saveCompanyInfo">保存修改</el-button>
            </template>
            <template v-else>
              <el-button type="primary" @click="startCompanyEdit">编辑企业信息</el-button>
            </template>
          </div>
        </div>
      </div>


      <!-- 基本信息 -->
      <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden" v-if="false">
        <div class="section-header flex justify-between items-center p-4 border-b border-gray-200">
          <h2 class="section-title text-lg font-semibold text-gray-800 flex items-center gap-2">
            <i class="fas fa-user text-blue-500"></i> 登录信息
          </h2>
        </div>
        <div class="section-body p-6">

          <div class="form-row grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">昵称</label>
              <el-input v-model="userInfoEdit.userName" class="w-full"></el-input>
              {{ userInfo.userName }}
            </div>
            <div class="form-group flex flex-col gap-1">
              <label class="form-label text-sm font-medium text-gray-500">微信</label>
              <span>
                <el-tag type="primary" @click="wechatFun">{{ userInfo.wechatBound ? '解除绑定微信' : '绑定微信' }}</el-tag>
              </span>
              {{ setSrc }}
              vxCode: {{ vxCode }}
              vxState: {{ vxState }}
              <el-input type="textarea" rows="3" @change="changeVxUrl" v-model="vxUrl"
                placeholder="请输入回调url"></el-input>
              <el-input v-model="vxCode" placeholder="请输入微信授权码"></el-input>
              <el-input v-model="vxState" placeholder="请输入微信授权状态"></el-input>
              <el-button @click="bindWechatFun">绑定微信</el-button>
              <iframe sandbox="allow-scripts allow-top-navigation allow-same-origin" scrolling="no" width="300"
                height="400" frameBorder="0" allowTransparency="true" :src="setSrc"></iframe>
            </div>
          </div>
        </div>
      </div>

      <!-- 账号安全 -->
      <div class="profile-section bg-white rounded-lg shadow-md mb-8 overflow-hidden">
        <div class="section-header flex justify-between items-center p-4 border-b border-gray-200">
          <h2 class="section-title text-lg font-semibold text-gray-800 flex items-center gap-2">
            <i class="fas fa-shield-alt text-blue-500"></i> 账号安全
          </h2>
        </div>
        <div class="section-body p-6">
          <div class="flex justify-between mb-4">
            <label class="form-label text-sm font-medium text-gray-500">登录名<span class="ml-2">{{ userInfo.userName
                }}</span></label>
            <el-button type="primary" @click="startEditUserName" style="width: 120px;">修改登录名</el-button>
          </div>
          <div class="flex justify-between mb-4">
            <label class="form-label text-sm font-medium text-gray-500">密码</label>
            <el-button type="primary" @click="updatePasswordFun" style="width: 120px;">修改密码</el-button>
          </div>
          <div class="flex justify-between mb-4">
            <label class="form-label text-sm font-medium text-gray-500">微信</label>
            <el-button type="primary" @click="wechatFun" style="width: 120px;">{{ userInfo.wechatBound ? '解除绑定微信' : '点击绑定微信'
            }}</el-button>
          </div>
          <!-- 改成弹窗 -->
          <el-dialog v-model="showVxContent" v-if="showVxContent" title="微信绑定" width="500">
            <iframe style="margin: 0 auto;" sandbox="allow-scripts allow-top-navigation allow-same-origin"
              scrolling="no" width="300" height="400" frameBorder="0" allowTransparency="true" :src="setSrc"></iframe>
          </el-dialog>

          <div class="form-group flex flex-col gap-1" v-if="false">
            <label class="form-label text-sm font-medium text-gray-500">登录设备管理</label>
            <button
              class="btn btn-outline bg-transparent border border-gray-200 text-gray-500 px-4 py-2 rounded-md text-sm font-medium transition-colors hover:border-blue-500 hover:text-blue-500 flex items-center gap-2 mt-1"
              @click="viewDevices">
              <i class="fas fa-laptop"></i> 查看登录设备
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="passwordDialogVisible" v-if="passwordDialogVisible" title="设置密码" width="500">
    <el-form ref="passwordForm" :model="passwordFormData" :rules="passwordRules" label-width="80px"
      class="password-form">
      <el-form-item label="旧密码" prop="oldPassword" v-if="hasPassword">
        <el-input v-model="passwordFormData.oldPassword" type="password" show-password placeholder="请输入旧密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordFormData.newPassword" type="password" show-password placeholder="请输入新密码"
          @input="checkPasswordStrength"></el-input>
        <div class="password-strength mt-2">
          <div class="strength-bar">
            <div class="strength-progress" :style="{ width: passwordScore + '%', backgroundColor: strengthColor }">
            </div>
          </div>
          <div class="strength-text" :style="{ color: strengthColor }">
            密码强度: {{ strengthLevel }}
          </div>
        </div>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordFormData.confirmPassword" type="password" show-password
          placeholder="请再次输入新密码"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">修改密码</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="userNameDialogVisible" v-if="userNameDialogVisible" title="设置登录名" width="500">
    <el-form ref="userNameForm" :model="userInfoEdit" @submit.native.prevent :rules="userNameRules" label-width="80px"
      class="password-form">
      <el-form-item label="登录名" prop="userName">
        <el-input v-model="userInfoEdit.userName" placeholder="请输入登录名"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="userNameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserName">修改登录名</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { EditPen } from '@element-plus/icons-vue';
import { getMyInfo, updateMyInfoEdit, updateUserName, bindWechat, unbindWechat, getWechatBindUrl, getUserPassword, changePassword } from "@/api/user";
import { getPublicKey } from "@/api/auth";
import { updateMyAvatarEdit } from "@/api/file";
import JSEncrypt from "jsencrypt";
import PasswordValidator from '@/utils/passwordValidator';

// 对话框控制
const dialogVisible = ref(false);
const errorTips = ref('');
const fileHead = ref([]); // 头像文件
const waitAvatar = ref(null);

// 登录名对话框控制
const userNameDialogVisible = ref(false);

// 编辑状态控制
const isEdit = ref(false);
const isCompanyEdit = ref(false);

// 用户基本信息
const userInfo = ref({
  nickName: '',
  signature: '',
  age: null,
  sex: '',
  city: '',
  wechat: '',
  avatar: '',
  phone: '',
  email: '',
  userName: ''
});

// 用户信息编辑对象
const userInfoEdit = ref({
  nickName: '',
  signature: '',
  age: null,
  sex: '',
  city: '',
  wechat: '',
  avatar: '',
  phone: '',
  email: '',
  userName: ''
});


// 性别文本显示
const genderText = computed(() => {
  const genderMap = {
    '1': '男',
    '2': '女',
    '0': '保密'
  };
  return genderMap[userInfo.value.sex] || '未知';
});

// 页面加载时获取用户信息
onMounted(() => {
  getMyInfoFun();
  getUserPasswordFun();
  window.addEventListener('message', handleMessage);
});

// 添加消息监听器
const handleMessage = (event) => {
  console.log('收到消息', event)
  // 验证消息来源 - 支持子域名
  const currentOrigin = window.location.origin;
  const eventOrigin = event.origin;

  // 检查是否是相同的域名（包括子域名）
  if (!eventOrigin.endsWith('.gotosea123.com')) {
    return;
  }

  if (event.data && event.data.type === 'wechat_login') {
    const code = event.data.code;
    const state = event.data.state;
    console.log('收到微信授权码:', code);
    vxCode.value = code;
    vxState.value = state;
    bindWechatFun();

    // 这里可以添加处理 code 的逻辑
  }
}

onUnmounted(() => {
  // 移除消息监听
  window.removeEventListener('message', handleMessage);
})

// 密码对话框控制
const passwordDialogVisible = ref(false);

const updatePasswordFun = () => {
  passwordFormData.value.oldPassword = '';
  passwordFormData.value.newPassword = '';
  passwordFormData.value.confirmPassword = '';
  passwordDialogVisible.value = true;
}

// 是否已经设置密码
const hasPassword = ref(false);

// 获取用户是否设置密码
const getUserPasswordFun = () => {
  getUserPassword().then(res => {
    if (res.suc) {
      console.log('获取用户密码成功', res);
      hasPassword.value = res.data
    }
  })
}

// 修改密码时获取公钥
// eslint-disable-next-line
const getPublicKeyFun = async () => {
  const res = await getPublicKey();
  console.log(res)
  return res.data
}

// 密码表单数据
const passwordFormData = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 密码强度相关
const passwordScore = ref(0);
const strengthLevel = ref('弱');
const strengthColor = ref('#ff4d4f');

// 检查密码强度
const checkPasswordStrength = () => {
  const score = PasswordValidator.getStrengthScore(passwordFormData.value.newPassword);
  const level = PasswordValidator.getStrengthLevel(score);

  passwordScore.value = score;
  strengthLevel.value = level.level;
  strengthColor.value = level.color;
};

// 修改密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const result = PasswordValidator.validate(value);
        if (!result.valid) {
          callback(new Error(result.message));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordFormData.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const userNameRules = {
  userName: [
    // 登录名只能包含字母、数字和下划线，长度在4-20个字符之间 
    { pattern: /^[a-zA-Z0-9_]{4,20}$/, message: '登录名只能包含字母、数字和下划线，长度在4-20个字符之间', trigger: 'blur' },
    { required: true, message: '请输入登录名', trigger: 'blur' }
  ]
}

const passwordForm = ref(null);

// 提交密码表单
const submitPasswordForm = async () => {
  if (!passwordForm.value) return;

  await passwordForm.value.validate(async (valid) => {
    if (valid) {
      const publicKey = await getPublicKeyFun();
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(publicKey);

      const encryptedOldPassword = encrypt.encrypt(passwordFormData.value.oldPassword);
      const encryptedNewPassword = encrypt.encrypt(passwordFormData.value.newPassword);
      const encryptedConfirmPassword = encrypt.encrypt(passwordFormData.value.confirmPassword);

      changePassword({
        oldPassword: encryptedOldPassword,
        newPassword: encryptedNewPassword,
        confirmPassword: encryptedConfirmPassword
      }).then(res => {
        if (res.suc) {
          ElNotification({
            title: '修改密码成功',
            type: 'success',
          })
          // 清空表单
          passwordForm.value.resetFields();
          passwordDialogVisible.value = false;
        } else {
          ElNotification({
            title: res.msg,
            type: 'error',
          })
        }
      });
    }
  });
};


// 获取用户信息
const getMyInfoFun = () => {
  getMyInfo().then(res => {
    if (res.suc) {
      console.log('获取用户信息成功', res);
      // 更新用户信息
      userInfo.value = {
        ...userInfo.value,
        ...res.data
      };
      waitAvatar.value = res.data.avatar;
    } else {
      ElNotification({
        title: '获取用户信息失败',
        type: 'error',
      })
    }
  }).catch(err => {
    console.error('获取用户信息错误', err);
    ElNotification({
      title: '获取用户信息出错',
      type: 'error',
    })
  });
};

// 开始编辑登录名
const startEditUserName = () => {
  userInfoEdit.value = { ...userInfo.value };
  userNameDialogVisible.value = true;
};

// 开始编辑用户信息
const startEdit = () => {
  isEdit.value = true;
  userInfoEdit.value = { ...userInfo.value };
};

// 取消编辑用户信息
const cancelEdit = () => {
  isEdit.value = false;
};

// 保存用户基本信息
const saveBasicInfo = () => {
  updateMyInfoEdit(userInfoEdit.value).then(res => {
    if (res.suc) {
      console.log('更新用户信息成功', res);
      userInfo.value = { ...userInfoEdit.value };
      isEdit.value = false;
      ElNotification({
        title: '基本信息保存成功！',
        type: 'success',
      })
    } else {
      ElNotification({
        title: res.msg,
        type: 'error',
      })
    }
  }).catch(err => {
    console.error('更新用户信息错误', err);
    ElNotification({
      title: '更新用户信息出错',
      type: 'error',
    })
  });
};

// 保存用户名
const saveUserName = () => {
  updateUserName({ username: userInfoEdit.value.userName }).then(res => {
    if (res.suc) {
      console.log('更新登录名成功', res);
      userInfo.value.userName = userInfoEdit.value.userName;
      ElNotification({
        title: '登录名更新成功！',
        type: 'success',
      })
      userNameDialogVisible.value = false;
    } else {
      ElNotification({
        title: res.msg,
        type: 'error',
      })
    }
  }).catch(err => {
    console.error('更新登录名错误', err);
    ElNotification({
      title: '更新登录名出错',
      type: 'error',
    })
  });
};

// 微信绑定相关
const wechatFun = () => {
  if (userInfo.value.wechatBound) {
    unbindWechatFun();
  } else {
    getWechatBindUrlFun();
  }
}

// 解绑微信
const unbindWechatFun = () => {
  if (!hasPassword.value) {
    ElNotification({
      title: '请先设置密码后再解绑微信',
      type: 'warning',
    })
    return;
  }

  ElMessageBox.confirm('确定解绑微信吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    unbindWechat().then(res => {
      if (res.suc) {
        console.log('解绑微信成功', res);
        ElNotification({
          title: '解绑微信成功',
          type: 'success',
        })
        getMyInfoFun();
      } else {
        ElNotification({
          title: res.msg,
          type: 'error',
        })
      }
    })
  })
}

// 获取微信绑定url
const getWechatBindUrlFun = () => {
  showVxContent.value = true;
  getWechatBindUrl().then(res => {
    if (res.suc) {
      setSrc.value = res.data.authUrl;
    }
  })
}

const setSrc = ref('');
const vxCode = ref('');
const vxState = ref('');
const vxUrl = ref('');

// 处理微信授权回调
const changeVxUrl = (val) => {
  // 将val中code 和state提取出来 
  const code = val.split('code=')[1].split('&')[0]
  const state = val.split('state=')[1].split('&')[0]
  vxCode.value = code
  vxState.value = state
}

const showVxContent = ref(false);

// 绑定微信
const bindWechatFun = () => {
  bindWechat({ code: vxCode.value, state: vxState.value }).then(res => {
    if (res.suc) {
      ElNotification({
        title: '绑定微信成功',
        type: 'success',
      })
      getMyInfoFun();
      showVxContent.value = false;
    } else {
      ElNotification({
        title: res.msg,
        type: 'error',
      })
      showVxContent.value = false;
    }
  })
}

// 头像上传相关方法
const requestUpload = () => {
  // 覆盖默认上传行为
};

// 头像上传前检查
const beforeUpload = (file) => {
  errorTips.value = '';
  // 检查文件类型
  if (file && file.type.indexOf("image/") == -1) {
    console.log("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    errorTips.value = "文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。";
    return false;
  }

  // 检查文件大小（限制为1MB）
  const maxSize = 1 * 1024 * 1024; // 1MB
  if (file.size > maxSize) {
    console.log("文件大小不能超过1MB");
    errorTips.value = "头像文件大小不能超过1MB";
    return false;
  }
  fileHead.value = file;
  waitAvatar.value = URL.createObjectURL(file);
  return true;
};

// 头像上传
const uploadImg = async () => {
  let formData = new FormData();
  formData.append("file", fileHead.value);
  updateMyAvatarEdit(formData).then(response => {
    if (response.suc) {
      dialogVisible.value = false;
      userInfo.value.avatar = waitAvatar.value;
      ElNotification({
        title: '头像更新成功',
        type: 'success',
      })
    } else {
      ElNotification({
        title: '头像更新失败',
        type: 'error',
      })
    }
  }).catch(err => {
    console.error('头像更新错误', err);
    ElNotification({
      title: '头像更新出错',
      type: 'error',
    })
  });
};

/*-----------------------------------企业信息-----------------------------------*/

// 企业信息
const companyInfo = reactive({
  name: '深圳市环球贸易有限公司',
  position: '跨境业务总监',
  scale: '11-50人',
  foundedDate: '2015-06-15',
  description: '深圳市环球贸易有限公司成立于2015年，是一家专注于跨境电商出口的综合型贸易企业，主营品类包括3C电子、家居用品等，年出口额超过5000万美元。'
});

// 企业信息编辑对象
const companyInfoEdit = ref({
  name: '',
  position: '',
  scale: '',
  foundedDate: '',
  description: ''
});

// 企业规模选项
const companyScales = [
  '10人以下',
  '11-50人',
  '51-200人',
  '201-500人',
  '501-1000人',
  '1000人以上'
];

// 账号安全信息
const securityInfo = reactive({
  phone: '138****5678',
  email: 'user****@example.com',
  twoFactor: true
});

// 开始编辑企业信息
const startCompanyEdit = () => {
  isCompanyEdit.value = true;
  companyInfoEdit.value = { ...companyInfo };
};

// 取消编辑企业信息
const cancelCompanyEdit = () => {
  isCompanyEdit.value = false;
};

// 保存企业信息
const saveCompanyInfo = () => {
  // 这里应该调用企业信息更新API
  // 模拟保存成功
  companyInfo.name = companyInfoEdit.value.name;
  companyInfo.position = companyInfoEdit.value.position;
  companyInfo.scale = companyInfoEdit.value.scale;
  companyInfo.foundedDate = companyInfoEdit.value.foundedDate;
  companyInfo.description = companyInfoEdit.value.description;

  isCompanyEdit.value = false;
  ElNotification({
    title: '企业信息保存成功！',
    type: 'success',
  })
};

// 账号安全相关方法
const changePhone = () => {
  ElNotification({
    title: '跳转到更换手机号页面',
    type: 'info',
  })
};

const changeEmail = () => {
  ElNotification({
    title: '跳转到更换邮箱页面',
    type: 'info',
  })
};

const viewDevices = () => {
  ElNotification({
    title: '跳转到登录设备管理页面',
    type: 'info',
  })
};


</script>

<style scoped>
.edit-icon {
  width: 30px;
  height: 30px;
  cursor: pointer;
}

.head-box img {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.recommend-head-box {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.recommend-head-item {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  width: 40px;
  height: 40px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.toggle-slider:before {
  content: "";
  position: absolute;
  height: 18px;
  width: 18px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: 0.3s;
  border-radius: 50%;
}

input:checked+.toggle-slider {
  background-color: #2563EB;
}

input:checked+.toggle-slider:before {
  transform: translateX(26px);
}

@media (max-width: 768px) {
  .avatar-section {
    flex-direction: column;
    align-items: flex-start;
  }

  .avatar-container {
    margin: 0 auto;
  }

  .avatar-upload {
    width: 100%;
    align-items: center;
  }

  .form-actions {
    flex-direction: column;
    gap: 0.5rem;
  }

  .btn {
    width: 100%;
  }
}

.password-strength {
  margin-top: 8px;
  width: 100%;
}

.strength-bar {
  height: 4px;
  background-color: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-progress {
  height: 100%;
  transition: all 0.3s;
}

.strength-text {
  font-size: 12px;
  margin-top: 4px;
}
</style>
